﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IQToolkit.Data.Common;
using Jmr.Entity.Poco;
using IQToolkit.Data.Mapping;

namespace Jmr.Entity.Poco
{
	public class JmrDatabaseMapping : AttributeMapping
	{
		DatabaseMapper _dbMap;
		Type _entityType;

		public JmrDatabaseMapping(QueryLanguage language, DatabaseMapper dbMap, Type entityType)
            : base(language, null)
      {
				_entityType = entityType;
				_dbMap = dbMap;
      }

		protected override IEnumerable<MappingAttribute> GetMappingAttributes(string tableName)
		{
			var map = _dbMap.GetMap(_entityType);
			var columnMaps = map.ColumnMaps;
			TableAttribute tableAttr = new TableAttribute();
			tableAttr.Name = map.TableName;
			var attrs = GetColumnMappingAttributes(columnMaps).ToList();
			attrs.Add(tableAttr);
			return attrs;
		}

		private IEnumerable<MappingAttribute> GetColumnMappingAttributes(List<ColumnMap> colMappings)
		{
			foreach (ColumnMap map in colMappings)
				yield return GetColumnMappingAttribute(map);
		}

		private MappingAttribute GetColumnMappingAttribute(ColumnMap element)
		{
			ColumnAttribute colAttr = new ColumnAttribute();
			colAttr.Member = element.PropertyName;
			colAttr.Name = element.ColumnName;
			colAttr.IsPrimaryKey = element.IsPrimaryKey;
			return colAttr;
		}
	}
}
